package com.school.fuyuan.framework.config.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.school.fuyuan.framework.config.param.DataSourcePropertiesData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author zrhong
 * @version 1.0
 * @date 2019/3/3 18:53
 * @description
 */
public class DruidConfiguration {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String DB_PREFIX = "spring.datasource";

    private final DataSourcePropertiesData data;

    public DruidConfiguration(DataSourcePropertiesData data) {
        this.data = data;
    }

    @Bean     //声明其为Bean实例
    @Primary  //在同样的DataSource中，首先使用被标注的DataSource
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(data.getUrl());
        datasource.setUsername(data.getUserName());
        datasource.setPassword(data.getPassword());
        datasource.setDriverClassName(data.getDriverClassName());

        //configuration
        datasource.setInitialSize(data.getInitialSize());
        datasource.setMinIdle(data.getMinIdle());
        datasource.setMaxActive(data.getMaxActive());
        datasource.setMaxWait(data.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(data.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(data.getMinEvictableIdleTimeMillis());
        datasource.setValidationQuery(data.getValidationQuery());
        datasource.setTestWhileIdle(data.isTestWhileIdle());
        datasource.setTestOnBorrow(data.isTestOnBorrow());
        datasource.setTestOnReturn(data.isTestOnReturn());
        datasource.setPoolPreparedStatements(data.isPoolPreparedStatements());
        datasource.setMaxPoolPreparedStatementPerConnectionSize(data.getMaxPoolPreparedStatementPerConnectionSize());
        try {
            datasource.setFilters(data.getFilters());
        } catch (SQLException e) {
            System.err.println("druid configuration initialization filter: " + e);
        }
        datasource.setConnectionProperties(data.getConnectionProperties());
        return datasource;
    }


}
